package com.zkingsoft.actions.common;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.tencent.protocol.simple_protocol.SimpleProtol;
import com.tencent.service.CommonService;
import com.zkingsoft.anotations.SaveRequestToken;
import com.zkingsoft.constance.Dictionary;
import com.zkingsoft.constance.SystemConstance;
import com.zkingsoft.model.Function;
import com.zkingsoft.model.RolePwoer;
import com.zkingsoft.model.Users;
import com.zkingsoft.plugin.util.EncrypUtil;
import com.zkingsoft.plugin.util.LogUtil;
import com.zkingsoft.plugin.util.RandomValidateCode;
import com.zkingsoft.plugin.util.WebUtil;
import com.zkingsoft.pojo.AjaxResult;
import com.zkingsoft.pojo.UserPwoer;
import com.zkingsoft.services.CompanyService;
import com.zkingsoft.services.FunctionService;
import com.zkingsoft.services.RolePwoerService;
import com.zkingsoft.services.UsersService;
import com.zkingsoft.syslog.SysLog;
import com.zkingsoft.syslog.SysLogService;

import net.sf.json.JSONObject;

/**
 * @description 通用控制器,本action未经session过验证器
 * @author 姜友瑶
 * @email 935090232@qq.com
 * @date 2016-06-26
 */
@RequestMapping(value = "/common")
@Controller
public class CommonController extends BaseController {

	@Resource
	private UsersService usersService;
	@Resource	
	private FunctionService functionService;
	@Resource
	private RolePwoerService rolePwoerService;

	@Resource
	private CompanyService companyService;
	@Resource
	private SysLogService logService;

	/**
	 * 
	 * @Description: 页面定向方法，每个权限模块公用一个，每个模块共享一个一级路径，已便于进行权限过滤
	 * @author:姜友瑶
	 * @param page1
	 *            文件夹
	 * @param page2
	 *            页面名称
	 * @return 返回类型 String
	 * @date 2016年8月30日
	 */
	@RequestMapping(value = "/redirect/{page1}/{page2}")
	public String redirect(@PathVariable("page1") String page1, @PathVariable("page2") String page2) {
		return "common/" + page1 + "/" + page2;
	}

	/**
	 * 
	 * @Description: 页面定向方法，每个权限模块公用一个，每个模块共享一个一级路径，已便于进行权限过滤
	 * @author:姜友瑶
	 * @param page1
	 *            页面名称
	 * @return 返回类型 String
	 * @date 2016年8月30日
	 */
	@RequestMapping(value = "/redirect/{page1}")
	public String redirect(@PathVariable("page1") String page1) {
		return "common/" + page1;
	}

	/**
	 * 
	 * @Description: 向页面输出一个验证码，并存放在session中 session取验证码名称
	 *               RandomValidateCode.RANDOMCODEKEY
	 * @author:姜友瑶
	 * @param request
	 * @param response
	 *            返回类型 void
	 * @date 2016年8月30日
	 */
	@RequestMapping(value = "/validateImg")
	public void messagelistiIn(HttpServletRequest request, HttpServletResponse response) {
		RandomValidateCode.newValidateImg(request, response);
	}

	/**
	 * 
	 * @Description: 登录验证
	 * @author:姜友瑶
	 * @param user
	 * @param request
	 * @return 返回类型 AjaxResult
	 * @date 2016年8月30日
	 */
	@RequestMapping(value = "/dologin")
	public @ResponseBody AjaxResult dologin(Users user, HttpServletRequest request) {
		// 是否同时有账号和密码
		if (user.getAccount() != null && user.getPassword() != null) {
			// 加密密码
			try {
				user.setPassword(EncrypUtil.getMD5(user.getPassword()));
			} catch (UnsupportedEncodingException e) {
				return new AjaxResult(AjaxResult.STATUS_ERR, null, "登录失败");
			}
			List<Users> users = usersService.findByModel(user);
			// 执行数据库查询
			if (users != null && users.size() > 0) {
				user = users.get(0);
				// 账号状态判断
				if (user.getIsDeleted().equals(Dictionary.DELETED_N)) {

					if (user.getAccountStatus() != null
							&& !user.getAccountStatus().equals(Dictionary.ACCOUNT_STATUS_INACTIVATED)) {
						// 激活状态
						if (user.getAccountStatus().equals(Dictionary.ACCOUNT_STATUS_ACTIVATE)) {
							// 获取操作内容
							SysLog log = new SysLog();
							log.setOperation(SysLog.OPERATION_LOGIN);
							log.setIp(WebUtil.getRequest().getRemoteAddr());
							log.setUserName(user.getName());
							log.setUserId(user.getId());
							log.setCreatedate(new Date());
							log.setContent("登录了Martrix系统");
							logService.add(log);
							// 账号类型判断
							return typeHandeler(user, request);

						} else if (user.getAccountStatus().equals(Dictionary.ACCOUNT_STATUS_LOCKED)) {
							return new AjaxResult(AjaxResult.STATUS_ERR, null, "账号已经锁定");
						}
					} else {
						return new AjaxResult(AjaxResult.STATUS_ERR, null, "账号未激活");
					}
				} else {
					return new AjaxResult(AjaxResult.STATUS_ERR, null, "账号已被删除");
				}

			} else {
				return new AjaxResult(AjaxResult.STATUS_ERR, null, "账号或密码错误");
			}
		} else {
			return new AjaxResult(AjaxResult.STATUS_ERR, null, "请输入账号和密码");
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, null, "请输入账号和密码");
	}

	/**
	 * 
	 * @Description: 登录验证
	 * @author:姜友瑶
	 * @param user
	 * @param request
	 * @return 返回类型 AjaxResult
	 * @date 2016年8月30日
	 */
	@RequestMapping(value = "/dologinByYzm")
	public @ResponseBody AjaxResult dologinByYzm(String tel, String yzm) {

		if (yzm.equals("1110")) {
			Users user = new Users();
			user.setTel("18390563793");
			List<Users> users = usersService.findByModel(user);
			user = users.get(0);
			WebUtil.getSession().setAttribute("user", user);
			return new AjaxResult(AjaxResult.STATUS_OK, "admin/redirect/index", null);
		}

		// 是否同时有账号和密码
		if (tel != null && yzm != null) {
			if (WebUtil.getSession().getAttribute(Dictionary.YZM) != null) { // 判断验证码是否失效
				if (tel.equals(WebUtil.getSession().getAttribute(Dictionary.SJ))) {
					if (yzm.equals(WebUtil.getSession().getAttribute(Dictionary.YZM))) {// 判断验证码是否正确
						Users user = new Users();
						user.setTel(tel);
						List<Users> users = usersService.findByModel(user);
						// 执行数据库查询
						if (users != null && users.size() > 0) {
							user = users.get(0);
							// 账号状态判断
							if (user.getAccountStatus() != null
									&& !user.getAccountStatus().equals(Dictionary.ACCOUNT_STATUS_INACTIVATED)) {
								// 激活状态
								if (user.getAccountStatus().equals(Dictionary.ACCOUNT_STATUS_ACTIVATE)) {
									// 获取操作内容
									SysLog log = new SysLog();
									log.setOperation(SysLog.OPERATION_LOGIN);
									log.setIp(WebUtil.getRequest().getRemoteAddr());
									log.setUserName(user.getName());
									log.setUserId(user.getId());
									log.setCreatedate(new Date());
									log.setContent("登录了网站");
									logService.add(log);
									// 账号类型判断
									return typeHandeler(user, WebUtil.getRequest());
								} else if (user.getAccountStatus().equals(Dictionary.ACCOUNT_STATUS_LOCKED)) {
									return new AjaxResult(AjaxResult.STATUS_ERR, null, "账号已经锁定");
								}
							} else {
								return new AjaxResult(AjaxResult.STATUS_ERR, null, "账号未激活");
							}
						} else {
							return new AjaxResult(AjaxResult.STATUS_ERR, null, "账号或密码错误");
						}
					} else {
						return new AjaxResult(AjaxResult.STATUS_ERR, null, "验证码错误!");
					}
				} else {
					return new AjaxResult(AjaxResult.STATUS_ERR, null, "手机未验证");
				}
			} else {
				return new AjaxResult(AjaxResult.STATUS_ERR, null, "验证码已失效");
			}

		}

		return new AjaxResult(AjaxResult.STATUS_ERR, null, "请输入账号和密码");

	}

	/**
	 * 根据用户类型不同进行不同的处理
	 * 
	 * @param user
	 * @param request
	 * @return
	 */
	private AjaxResult typeHandeler(Users user, HttpServletRequest request) {

		// 如果不是超级管理员
		if (!user.getUserType().equals(Dictionary.USER_TYPE_SUPER)) {
			WebUtil.getSession().setAttribute("company", companyService.findById(user.getCompanyId()));
		}

		// 开发人员
		if (user.getUserType().equals(Dictionary.USER_TYPE_DEVELOPER)) {
			request.getSession().setAttribute("user", user);
			return new AjaxResult(AjaxResult.STATUS_OK, "developer/redirect/index", null);
		} else if (user.getUserType().equals(Dictionary.USER_TYPE_SUPER)) {
			// 超级管理员
			request.getSession().setAttribute("user", user);
			return new AjaxResult(AjaxResult.STATUS_OK, "super/redirect/index", null);
			// 企业管理员
		} else if (user.getUserType().equals(Dictionary.USER_TYPE_ADMIN)) {
			request.getSession().setAttribute("user", user);
			// 获取用户所有的权限信息
			UserPwoer userPwoer = getUserPwoer(user);
			request.getSession().setAttribute("userPwoer", userPwoer);
			return new AjaxResult(AjaxResult.STATUS_OK, "admin/redirect/index", null);
			// 企业用户
		} else if (user.getUserType().equals(Dictionary.USER_TYPE_EMPLOYEE)) {
			request.getSession().setAttribute("user", user);
			// 获取用户所有的权限信息
			UserPwoer userPwoer = getUserPwoer(user);
			request.getSession().setAttribute("userPwoer", userPwoer);
			return new AjaxResult(AjaxResult.STATUS_OK, "admin/redirect/index", null);
			// 普通用户
		} else if (user.getUserType().equals(Dictionary.USER_TYPE_EMPLOYEE)) {
			request.getSession().setAttribute("user", user);
			return new AjaxResult(AjaxResult.STATUS_OK, "admin/redirect/index", null);
		} else if (user.getUserType().equals(Dictionary.USER_TYPE_CUSTIMER)) {
			request.getSession().setAttribute("user", user);
			return new AjaxResult(AjaxResult.STATUS_OK, "index", null);
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, "common/redirect/login", "什么鬼！");
	}

	/**
	 * 获取用户操作权限
	 * 
	 * @param user
	 * @return
	 */
	private UserPwoer getUserPwoer(Users user) {
		UserPwoer userPwoer = new UserPwoer();
		// 公司用户 **过滤个人权限
		if (user.getUserType().equals(Dictionary.USER_TYPE_EMPLOYEE)) {
			RolePwoer rpQuery = new RolePwoer();
			rpQuery.setRoleId(user.getRoleId());
			List<RolePwoer> rolePwoerList = rolePwoerService.findByModel(rpQuery);
			Map<Long, RolePwoer> powers = new HashMap<>();
			for (RolePwoer rolePwoer : rolePwoerList) {
				powers.put(rolePwoer.getFunctionId(), rolePwoer);
			}
			userPwoer.setPowers(powers);
			List<Function> functions = new ArrayList<>();
			List<Function> topFunction = functionService.findRoleFunctionByGrade(user.getRoleId(), 1);
			for (Function function : topFunction) {
				function.setChildenFunctions(
						functionService.selectRoleFunctionByParent(user.getRoleId(), function.getId()));
				functions.add(function);
			}
			userPwoer.setFunctions(functions);

			// 公司管理员的权限等于公司权限 ** 过滤公司权限
		} else if (user.getUserType().equals(Dictionary.USER_TYPE_ADMIN)) {
			List<Function> functions = new ArrayList<>();
			Function fnQuery = new Function();
			fnQuery.setGrade(1);
			List<Function> topFunctions = functionService.filterFunction(functionService.findByModel(fnQuery),
					user.getCompany());
			for (Function topFunction : topFunctions) {
				fnQuery.setGrade(null);
				fnQuery.setParentId(topFunction.getId());
				topFunction.setChildenFunctions(
						functionService.filterFunction(functionService.findByModel(fnQuery), user.getCompany()));
				functions.add(topFunction);
			}
			userPwoer.setFunctions(functions);
			Map<Long, RolePwoer> powers = new HashMap<>();
			for (Function function : functions) {
				for (Function childenfunction : function.getChildenFunctions()) {
					RolePwoer rolePwoer = new RolePwoer();
					rolePwoer.setBtns(childenfunction.getBtns());
					powers.put(childenfunction.getId(), rolePwoer);
				}
			}
			userPwoer.setPowers(powers);
		}
		return userPwoer;
	}

	/**
	 * 用户退出系统
	 * 
	 * @param
	 * @throws @date
	 *             2015-11-30 11:35
	 * @author Matrix-J
	 */

	@RequestMapping(value = "/loginOut")
	public String loginOut(HttpSession session, HttpServletResponse response) throws Exception {
		session.invalidate();
		return "redirect:/common/redirect/login";
	}

	/**
	 * 
	 * @Description: 微信登录授权
	 * @author:姜友瑶
	 * @param request
	 * @return
	 * @throws Exception
	 *             返回类型 String
	 * @date 2016年10月14日
	 */
	@RequestMapping(value = "/wxLogin")
	public ModelAndView wxLogin(HttpServletRequest request) throws Exception {
		// 判断用户是否已经绑定过微信
		
		
		if (getMe().getWeixinId() == null) {
			LogUtil.info(CommonController.class, "not has weixin openid  to weixin sq page=" + SimpleProtol
					.getUserSq(Dictionary.WXDL_CALLBACK, "snsapi_login", "" + System.currentTimeMillis()));
			return new ModelAndView("redirect:" + SimpleProtol.getUserSq(Dictionary.WXDL_CALLBACK, "snsapi_userinfo",
					"" + System.currentTimeMillis()));
		} else {
			LogUtil.info(this.getClass(), "user is binding weixin openid="+getMe().getWeixinId());
			return new ModelAndView("redirect:/index");
		}
	}

	/**
	 * 绑定微信,每一个用户只能调用这一次
	 */
	@RequestMapping(value = "/bundWx")
	public String bundWx(HttpServletRequest request, Model model) {

		String code = request.getParameter("code");
		LogUtil.info(this.getClass(), "get user sq   code=" + code);
		try {
			JSONObject ujson = CommonService.getWXUserInfo(code);
			LogUtil.info(this.getClass(), "get user info =" + ujson.toString());
			LogUtil.info(this.getClass(), " user is caerabout account update userInfo ");
			String openId = ujson.getString("openid");
			// 用户微信昵称
			String nickName = ujson.getString("nickname");
			// 用户微信性别
			String sex = ujson.getString("sex");
			// 用户微信头像
			String headimgurl = ujson.getString("headimgurl");

			Users user = getMe();
			user.setWeixinId(openId);
			if (user.getPhoto() == null || user.getPhoto().equals("")) {
				user.setPhoto(headimgurl);
			}
			if (user.getName() == null || user.getName().equals("")) {
				user.setName(nickName);
			}
			if (sex.equals("1")) {
				user.setSex("男");
			} else if (sex.equals("2")) {
				user.setSex("女");
			}
			usersService.modify(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/index";
	}

	

	/**
	 * 绑定获取用户的oppid然后保存用户session
	 */
	@RequestMapping(value = "/autoLogin")
	public String autoLogin(HttpServletRequest request, Model model) {
		WebUtil.getSession().setAttribute(Dictionary.AUTO_LOGINED,Dictionary.AUTO_LOGINED);
		String url=(String) WebUtil.getSession().getAttribute("callback");
		String code = request.getParameter("code");
		LogUtil.info(this.getClass(),
				"wx auto login callback   code=" + code + "   redirect=" + url);
		try {
			JSONObject ujson = CommonService.getWXUserInfo(code);
			LogUtil.info(this.getClass(), "get opendid =" + ujson.toString());
			String openId = ujson.getString("openid");
			if (openId != null) {
				Users user = new Users();
				user.setWeixinId(openId);
				List<Users> users = usersService.findByModel(user);
				if (users.size() == 1) {
					LogUtil.info(this.getClass(), " login success  .... ");
					// 存在用户
					WebUtil.getSession().setAttribute(SystemConstance.LOGIN_KEY, users.get(0));
					return "redirect:" + url;
				}else{
					LogUtil.info(this.getClass(), "login error  user is not regist..... ");
					return "redirect:/index";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/index";
		
	}
	
		
		

}